import axios from "axios";
import { ElMessage, ElLoading } from "element-plus";
import router from "@/router";

// 创建 axios 实例
const service = axios.create({
  baseURL: "http://localhost:8234",
  timeout: 5000,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
});

// 请求计数器
let loadingCount = 0;
let loadingInstance = null;

// 显示加载
const showLoading = () => {
  if (loadingCount === 0) {
    loadingInstance = ElLoading.service({
      text: "加载中...",
      background: "rgba(0, 0, 0, 0.7)",
    });
  }
  loadingCount++;
};

// 隐藏加载
const hideLoading = () => {
  loadingCount--;
  if (loadingCount === 0 && loadingInstance) {
    loadingInstance.close();
    loadingInstance = null;
  }
};

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    console.log("请求拦截器执行", config.url);
    // 显示加载动画
    if (!config.hideLoading) {
      showLoading();
    }
    // 添加时间戳防止缓存
    if (config.method === "get") {
      config.params = {
        ...config.params,
        _t: Date.now(),
      };
    }
    // 如果不是文件下载请求，设置默认的 Content-Type
    if (!config.responseType || config.responseType !== "blob") {
      config.headers["Content-Type"] = "application/json";
    }
    if (config.url !== "/user/login" && config.url !== "/user/register") {
      const user = JSON.parse(window.sessionStorage.getItem("user"));
      if (user && user.token) {
        config.headers["token"] = user.token;
        console.log("设置 token", user.token);
      } else {
        console.log("设置token失败");
        router.push("/login");
      }
      if (user.token) {
        config.headers["Authorization"] = `Bearer ${user.token}`;
      }
    }
    console.log("Request Config:", config);
    return config;
  },
  (error) => {
    hideLoading();

    ElMessage.error({ message: error.message });
    console.error("请求拦截器错误", error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    hideLoading();

    console.log("响应拦截器执行", response.status, response.data);
    // 如果是文件下载请求，直接返回完整的响应对象
    if (response.config.responseType === "blob") {
      return response;
    }
    if (response.status && response.status === 200) {
      if (response.data.code === 401) {
        Storage.removeSession("user");
        router.push("/login");
      }
      if (
        response.data.code === 500 ||
        response.data.code === 401 ||
        response.data.code === 403
      ) {
        ElMessage.error({ message: response.data.message });
        return Promise.reject(response.data);
      }
      if (response.data.message) {
        ElMessage.success({ message: response.data.message });
      }
    }
    return response.data;
  },
  (error) => {
    hideLoading();

    const status = error.response ? error.response.status : null;
    console.log(error);
    let message = "请求失败，请检查网络或服务器";
    if (status === 504 || status === 404) {
      message = "服务器出错";
    } else if (status === 403) {
      message = "权限不足，请联系管理员";
    } else if (status === 401) {
      message = "请登录账号";
      Storage.removeSession("user");
      router.replace("/login");
    } else if (
      error.response &&
      error.response.data &&
      error.response.data.message
    ) {
      message = error.response.data.message;
    }
    ElMessage.error({ message });
    console.error("响应拦截器错误", error);
    return Promise.reject(error);
  }
);

// 封装 GET 请求
export function get(url, params, config = {}) {
  return service.get(url, { params, ...config });
}

// 封装 POST 请求
export function post(url, data, config = {}) {
  return service.post(url, data, config);
}

// 封装 PUT 请求
export function put(url, data, config = {}) {
  return service.put(url, data, config);
}

// 封装 DELETE 请求
export function del(url, params, config = {}) {
  return service.delete(url, { params, ...config });
}

// 封装上传文件请求
export function upload(url, file, config = {}) {
  const formData = new FormData();
  formData.append("file", file);
  return service.post(url, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
    ...config,
  });
}

// 封装下载文件请求
export function download(url, params, config = {}) {
  return service.get(url, {
    params,
    responseType: "blob",
    ...config,
  });
}

// 取消请求
export const CancelToken = axios.CancelToken;

export default service;
